<template lang="pug">
  h4 Suite
  form(@submit.prevent="handleSubmit")
    input(type="text", v-model.trim="formData.name" placeholder="name")
    select(v-model="formData.medium")
      option(disabled, value="undefined") media
      option(v-for="medium in media" :key="medium.id" :value="medium.value") {{medium.name}}
    br
    select(v-model="formData.based")
      option(disabled, value="undefined") based on
      option(v-for="based in baseds" :key="based.id" :value="based.value") {{based.name}}

    select(v-model="formData.unit")
      option(disabled, value="undefined") unit
      option(v-for="unit in units[formData.medium]" :key="unit.id" :value="unit.value") {{unit.name}}

    select(v-model="formData.colorMode")
      option(disabled, value="undefined") color mode
      option(v-for="mode in modes[formData.medium]" :key="mode.id" :value="mode.value") {{mode.name}}

    br
    label(for="checkbox") 
      input(type="checkbox" id="checkbox" v-model="formData.useAspectRatio" )
      span use aspect ratio &nbsp;&nbsp;
    label(for="checkbox")
      input(type="checkbox" id="checkbox" v-model="formData.usePercentSize" :disabled="formData.useAspectRatio")
      span use percent
    br
    button(type="submit" :disabled="submitDisabled") create suite
    button(@click="resetFormData") Reset
</template>

<script setup>
import { computed, ref, onMounted, watch, inject } from 'vue';
import { baseds, units, media, modes, unitMathcModes } from './suite-constants'
import api from '../../apis/api'
import { checkFormData } from '../../utils/js.util'

const mainBrandId = inject('mainBrandId')
const formData = ref({
  name: undefined,
  brandId: undefined,
  medium: 'web',
  based: 'short',
  unit: units.web[0].value,
  colorMode: modes.web[0].value,
  useAspectRatio: false,
  usePercentSize: true,
})

watch(() => formData.value.useAspectRatio, (use) => {
  if (use) formData.value.usePercentSize = true
})
watch(() => formData.value.medium, (val) => {
  formData.value.unit = units[val][0].value
  formData.value.colorMode = modes[val][0].value
})

watch(() => formData.value.unit, (val) => {
  formData.value.colorMode = unitMathcModes[val]
})

const initialFormData = { ...formData.value }
const handleSubmit = async () => {
  const result = await api.post('suites', { ...formData.value })
  resetFormData()
};

const resetFormData = () => {
  for (let key in initialFormData) {
    formData.value[key] = initialFormData[key];
  }
};

watch(mainBrandId, async () => formData.value.brandId = mainBrandId.value)
const submitDisabled = computed(() => !checkFormData(formData.value))
</script>
